﻿using HalconDotNet;
using Halcon二次开发.Controller.CamerForm交互;
using Halcon二次开发.Controller.主界面交互;
using Halcon二次开发.Controller.卡尺;
using Halcon二次开发.Model;
using Halcon二次开发.Model.储存每个Controller的单例对象;
using Halcon二次开发.Model.储放所有单例.储存每个单例界面;
using Halcon二次开发.Model.自定义控件;
using Halcon二次开发.Tools;
using Halcon二次开发.View.输入框;
using log4net;
using log4net.Config;
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Halcon二次开发.Controller.数据加载与保存;
using System.Reflection;
using Halcon二次开发.View.多模板匹配;
using Halcon二次开发.View.Socket通信;
using MvCameraControl;
using Halcon二次开发.View.精准测量模块;
using Halcon二次开发.View.应用_加载框;
using Halcon二次开发.View.工位监控画面;
using Halcon二次开发.View.登录界面;
using Halcon二次开发.View.账号信息界面;
using Halcon二次开发.View.配置界面;
using Halcon二次开发.Model.配置信息;
using System.Xml.Linq;
using Halcon二次开发.View.相机;
using System.Net.NetworkInformation;
using 可视化工具.View.创建工程;
using 可视化工具.Model.工程文件保存属性类;
using System.Collections.Generic;
using System.Threading;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using System.Linq;
using 可视化工具.View.输入框;
using System.Net;
using System.Diagnostics;
using System.Threading.Tasks;

[assembly: XmlConfigurator(ConfigFile = "Data\\日志配置文件\\log4net.config", Watch = true)]
namespace Halcon二次开发
{
    public partial class Form1 : Form
    {
        //控制监视磁盘线程的变量
        public static bool delImagePaper = true;
        //控制进行工程文件的标志
        public bool getHomeFormPaper = true;
        /// <summary>
        /// 工程文件路径
        /// </summary>
        public string filePath = $@"Data\工程文件\";//创建文件时会修改这个工程的默认路径
        /// <summary>
        /// 程序默认路径
        /// </summary>
        public string approvePath = $@"Data\工程文件\";//这个路径是不会修改的
        /// <summary>
        /// 当前工程文件的名称
        /// </summary>
        public string projectName = null;
        //日志文件对象
        public static readonly ILog log = LogManager.GetLogger(typeof(Form1));
        //程序加载界面
        Form load;
        public Form1(LoadForm loadForm)
        {
            this.load = loadForm;
            InitializeComponent();
            //单例窗体
            FormDb.Db.Add("Form1", this);
            HOperatorSet.SetSystem("clip_region", "false");
            //获取最大线程数
            //ThreadPool.GetMinThreads(out int minWokerThreads,out int minCompletionPortThreads);
            //ThreadPool.GetMaxThreads (out int maxWokerThreads, out int maxCompletionPortThreads);

            //ThreadPool.SetMinThreads(  minWokerThreads,   minCompletionPortThreads);
            //ThreadPool.SetMaxThreads(  maxWokerThreads*5,   maxCompletionPortThreads*5);
        }
        /// <summary>
        /// 双击添加流程节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            int index = tabControl2.SelectedIndex;
            if (index == -1)
            {
                textBox1.AppendText("请先添加工程文件!\r\n");
                return;
            }
            HwindowFlowNodeUrseControl s = tabControl2.TabPages[index].Tag as HwindowFlowNodeUrseControl;
            string iii = s.name;
            string iiiii = s.projectName;
            int pp = StaicResouce.HomeForms.Count;
            //这里要判断一下
            foreach (var item in StaicResouce.formCollections)
            {
                if (item.name == tabControl2.TabPages[index].Text&& s==item.hwindowFlowNode)
                {
                    item.Btn_Double_Click(s, treeView1);
                    break;
                }
            }
        }
        /// <summary>
        /// 新建任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 新建任务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //获取菜单栏的上一个父级    openNameCreate:当前创建文件的工程名称
            string openNameCreate = ((ToolStripMenuItem)sender).OwnerItem.Text;
            //如果filePath路径没变那么就是不能去创建工程文件了
            if (!ShowFilePathNULL())
            {
                textBox1.AppendText("新建任务失败!\r\n");
                return;
            }
            string[] silpName = openNameCreate.Split(new char[] { '工', '程', '文', '件' });
            if (projectName != silpName[0])
            {
                textBox1.AppendText("请选择该工程再进行增加任务!\r\n");
                return;
            }
            //路径选择窗口
            NameForm nameForm = new NameForm(projectName);
            nameForm.fathName = silpName[0];//将当前工程名字给到文件路径选择
            nameForm.ShowDialog(this);
            if (nameForm.name == "")
            {
                return;
            }
            else if (nameForm.name.Contains("任务文件"))
            {
                MessageBox.Show("文件名不能包含\"任务文件\"");
            }
            //将这个新增的菜单添加到对应的菜单中.DropDownItems.Add(nameForm.name + "任务文件");
            ToolStripMenuItem t1 = (ToolStripMenuItem)((ToolStripMenuItem)sender).OwnerItem;
            ToolStripMenuItem addsToolStream = new ToolStripMenuItem(nameForm.name + "任务文件");
            t1.DropDownItems.Add(addsToolStream);
            ToolStripMenuItem delToolStream = new ToolStripMenuItem("-删除任务-");
            addsToolStream.DropDownItems.Add(delToolStream);//增加一个删除任务
            delToolStream.Click += MenuItemMove_Click;//点击删除任务事件
            //添加界面 
            HwindowFlowNodeUrseControl hwindowFlowNodeUrseControl = new HwindowFlowNodeUrseControl();
            //对这个动作进行新增
            Form1Controller form1Controller = new Form1Controller();
            form1Controller.name = nameForm.name;
            //将大工程名字给到FormController
            form1Controller.SetFilePath(projectName);
            form1Controller.hwindowFlowNode = hwindowFlowNodeUrseControl;  //绑定上去,代替静态变量
            StaicResouce.formCollections.Add(form1Controller);
            //这俩步非常重要,动作绑定窗体
            hwindowFlowNodeUrseControl.name = nameForm.name;
            hwindowFlowNodeUrseControl.projectName = projectName;//所属的操作工程名
            hwindowFlowNodeUrseControl.form1Controller = form1Controller;
            //MonitoringForm.GetMonitoringForm().AddFramesTime(hwindowFlowNodeUrseControl);
            hwindowFlowNodeUrseControl.framesTimeForm = new FramesTimeForm(hwindowFlowNodeUrseControl, MonitoringForm.GetMonitoringForm());
            MonitoringForm.GetMonitoringForm().Hide();
            Utiy.AddPage(hwindowFlowNodeUrseControl, tabControl2, nameForm.name);
            //对这个新增的页面进行记录
            StaicResouce.HomeForms.Add(hwindowFlowNodeUrseControl);
            //刷新配置界面
            ConfigForm.GetSingle().Push_Data();
        }
        /// <summary>
        /// Tab页更改时发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabControl2_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = tabControl2.SelectedIndex;
            if (index == -1) return;
            HwindowFlowNodeUrseControl s = tabControl2.TabPages[index].Tag as HwindowFlowNodeUrseControl;

            StaicResouce.HwindowFlowNodeUrse = s;
        }
        //Text消息框更改,写入日志文件
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            log.Error(textBox1.Text);
        }
        /// <summary>
        /// 预加载数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            //加载工程文件的默认路径@"Data\默认工程文件保存\上一次工程名称.json"
            string paths = @"Data\默认工程文件保存\上一次工程名称.json";
            ProjectDomain domain = HelpJsons.ReadObject<ProjectDomain>(paths);
            if (domain != null)
            {
                //对当前工程文件名进行赋值
                filePath = domain.path;
                projectName = domain.name;
            }
            string state = approvePath + projectName;//根目录 //例子 ：\Data\工程文件    
            //加载工程文件到菜单栏上
            AddPreloadMenuItemStrip();
            if (Directory.Exists(state))
            {
                string[] stateS = Directory.GetDirectories(state);// 查询所有工程文件
                // 将子文件夹路径转换为DirectoryInfo对象，以便访问修改时间
                var directories = stateS.Select(path => new DirectoryInfo(path)).ToList();
                // 按照修改时间排序（升序）
                directories.Sort((dir1, dir2) => dir1.CreationTime.CompareTo(dir2.CreationTime));
                foreach (var item in directories)//循环创建所有任务文件
                {
                    LoadStation(item.FullName);
                }
                if (stateS.Length > 0)
                {
                    tabControl2.SelectedIndex = 0;
                }
                splitContainer1.SplitterDistance = splitContainer1.Height / 3 * 2;
            }
            //加载配置信息

            //首先要判断存在配置文件
            if (!Directory.Exists(@"Data\配置文件"))
            {
                Directory.CreateDirectory(@"Data\配置文件");
            }
            if (!File.Exists(@"Data\配置文件\AppConfig.config"))
            {
                File.Create(@"Data\配置文件\AppConfig.config").Close();
            }
            string[] configstr = File.ReadAllLines(@"Data\配置文件\AppConfig.config");
            MonitoringForm.GetMonitoringForm(this).Show();//显示工位界面
            this.Hide();//隐藏主界面
            if (configstr.Length < 1) return;
            PathConfig.GetSingle().DiskValue = configstr[0];

        }
        int find_index = 0;
        string find_path = "";
        string find_name = "";
        /// <summary>
        /// 递归查找有没有相同的任务文件
        /// </summary>
        /// <param name="path"></param>
        public void Find_Directory(string path)
        {
            string[] strs = path.Split(new char[] { '\\' });
            if (Directory.Exists(path))
            {
                find_index++;
                string endPath = "";
                //string endPath = strs[strs.Length - 1];
                //endPath = endPath.Substring(0,endPath.IndexOf("任"));
                for (int i = 0; i < strs.Length; i++)
                {
                    if (i != strs.Length - 1)
                    {
                        endPath += strs[i];
                        endPath += "\\";
                    }
                    else
                    {
                        string str = strs[i].Substring(0, strs[i].IndexOf("任"));
                        find_name = str + "副本_" + find_index + "任务文件";
                        endPath += str + "副本_" + find_index + "任务文件";
                    }
                }
                find_path = endPath;
                Find_Directory(find_path);
            }
            else
            {
                find_name = strs[strs.Length - 1];
            }
        }

        /// <summary>
        /// 加载工程文件
        /// </summary>
        /// <param name="destDir"></param>
        private void LoadStation(string destDir, string paper = "", string copyPaper = "")
        {
            try
            {
                //重新覆盖任务文件-补丁
                if (copyPaper == "打开任务")
                {
                    string[] strs = destDir.Split(new char[] { '\\' });
                    string endPath = "";//string endPath = projectName;
                    for (int i = 0; i < strs.Length; i++)
                    {
                        if (i == strs.Length - 2)
                        {
                            endPath += projectName + "\\";
                            continue;
                        }
                        endPath += strs[i];
                        if (i != strs.Length - 1)
                        {
                            endPath += "\\";
                        }
                    }
                    //这里要校验一下有没有重复的任务文件
                    Find_Directory(endPath);
                    if (find_path == "")
                    {
                        find_path = endPath;
                    }
                    CopyDirectory(destDir, find_path);
                    destDir = find_path;
                }


                //将任务名提取出来
                string[] stateName = destDir.Split(new char[] { '任', '务', '文', '件', '\\' }, StringSplitOptions.RemoveEmptyEntries);
                string name = stateName[stateName.Length - 1];

                int paperOpen = -1;
                foreach (string item in StaicResouce.FilesName.Keys)
                {
                    if (item.Equals(projectName))
                    {
                        paperOpen = 1;
                    }
                }
                if (paperOpen == -1)
                {
                    StaicResouce.FilesName.Add(projectName, name);
                }

                //需要校验,该页面有没有添加
                int formIndex = -1;
                for (int i = 0; i < StaicResouce.HomeForms.Count; i++)
                {
                    string iii = ((HwindowFlowNodeUrseControl)StaicResouce.HomeForms[i]).name;
                    //判断这个工程是否存在
                    if (((HwindowFlowNodeUrseControl)StaicResouce.HomeForms[i]).projectName == projectName && ((HwindowFlowNodeUrseControl)StaicResouce.HomeForms[i]).name == name)
                    {
                        formIndex = i;
                        break;
                    }
                }

                //***********************************


                Form1Controller form1controller = null;
                foreach (Form1Controller item in StaicResouce.formCollections)
                {
                    if (projectName == item.projectName && name == item.name)
                    {
                        form1controller = item;
                        break;
                    }
                }

                if (form1controller == null)
                {
                    
                    StaicResouce.homeContolrName.Add(name);
                    // projectName:工程名称    nameForm.name：任务名称
                    //对这个动作进行新增
                    form1controller = new Form1Controller();
                    form1controller.name = name;
                    form1controller.projectName = projectName;
                    //将大工程名字给到FormController

                    foreach (var item in StaicResouce.formCollections)
                    {
                        if (form1controller.name==item.name&& form1controller.projectName==projectName)
                        {
                            StaicResouce.formCollections.Remove(item);
                            break;
                        }
                    }

                    form1controller.SetFilePath(projectName);
                    StaicResouce.formCollections.Add(form1controller);
                }




                //***********************************




                //添加界面
                HwindowFlowNodeUrseControl hwindowFlowNodeUrseControl = new HwindowFlowNodeUrseControl();
                //刷新控件对象
                if (formIndex != -1)
                {
                    StaicResouce.HomeForms[formIndex] = hwindowFlowNodeUrseControl;
                }
                //这俩步非常重要,动作绑定窗体
                hwindowFlowNodeUrseControl.name = name;
                hwindowFlowNodeUrseControl.projectName = form1controller.projectName;
                hwindowFlowNodeUrseControl.form1Controller = form1controller;
                
                //实时监控图像
                //MonitoringForm hObject = MonitoringForm.GetMonitoringForm();
                MonitoringForm.GetMonitoringForm(hwindowFlowNodeUrseControl).AddFramesTime(hwindowFlowNodeUrseControl);
                //MonitoringForm.GetMonitoringForm().GetHSmartWindow(name);)
                hwindowFlowNodeUrseControl.framesTimeForm = new FramesTimeForm(hwindowFlowNodeUrseControl, MonitoringForm.GetMonitoringForm(hwindowFlowNodeUrseControl));
                //MonitoringForm.GetMonitoringForm().GetHSmartWindow(name).Show();
                //TODO: 这条需要赋值一下,因为第一次Page页选择事件不会被触发
                //StaicResouce.HwindowFlowNodeUrse = hwindowFlowNodeUrseControl;
                Utiy.AddPage(hwindowFlowNodeUrseControl, tabControl2, name);

                //设置工位hwindowFlowNode
                form1controller.SethwindowFlowNode();


                //对这个新增的页面进行记录
                if (paper != "开启")//当不是切换，不进行添加
                {
                    StaicResouce.HomeForms.Add(hwindowFlowNodeUrseControl);
                }


                bool addPaper = false;
                foreach (HwindowFlowNodeUrseControl item in StaicResouce.HomeForms)
                {
                    //判断这个工程是否存在
                    if (item.projectName == projectName && item.name == name)
                    {
                        addPaper = true;
                    }
                }
                //如果这个工程不存在就是打开的工程
                if (!addPaper)
                {
                    StaicResouce.HomeForms.Add(hwindowFlowNodeUrseControl);
                }




                //遍历流程文件 创建项目流程
                string flowFile = destDir + "\\流程\\流程.txt";
                if (File.Exists(flowFile))
                {
                    string[] tools = File.ReadAllLines(flowFile);
                    for (int i = 0; i < tools.Length; i++)
                    {
                        string[] results = tools[i].Split(new char[] { ',', ':' }, StringSplitOptions.RemoveEmptyEntries);
                        object classInstance = CreateObjectByName(results[0], hwindowFlowNodeUrseControl);
                        //这里就是2个PMA模板匹配所需的构造方法
                        if (classInstance is H_PMA_S_AlignToolForm)
                        {
                            (classInstance as H_PMA_S_AlignToolForm).SetPathNodes(approvePath + projectName + "\\" + hwindowFlowNodeUrseControl.name + "任务文件", results[2].Trim());
                        }
                        if ((classInstance is Form))
                        {
                            //获取到每个类中的SetJsonPaths方法
                            MethodInfo methodInfo = classInstance.GetType().GetMethod("SetJsonPaths");
                            if (methodInfo != null)
                            {
                                object[] objs = new object[2] { approvePath + projectName + "\\" + hwindowFlowNodeUrseControl.name + "任务文件", results[2].Trim() };
                                methodInfo.Invoke(classInstance, objs);
                            }
                            form1controller.AddHeadNode((classInstance as Form), results[2].Trim(), hwindowFlowNodeUrseControl, int.Parse(results[3]));
                            foreach (TreeNode targetNode in hwindowFlowNodeUrseControl.treeView1.Nodes)
                            {
                                if (targetNode.Name == results[2].Trim())
                                {
                                    //更改子节点的连接状态 
                                    AddChildLink(ref i, tools, targetNode);
                                }
                            }
                        }

                        if (classInstance is CaliperModuleForm)
                        {
                            if (classInstance == null) continue;
                            foreach (TabPage pag in (classInstance as CaliperModuleForm).ParentPanl.TabPages)
                            {
                                if (pag == null || pag.Tag == null) continue;

                                MethodInfo methodInfo = pag.Tag.GetType().GetMethod("SetJsonPaths");
                                if (methodInfo != null)
                                {
                                    object[] objs = new object[2] { approvePath + projectName + "\\" + hwindowFlowNodeUrseControl.name + "任务文件", results[2].Trim() };
                                    methodInfo.Invoke(pag.Tag, objs);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
        /// <summary>
        /// 删除工程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void 删除工程toolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                //拿到工程节点
                ToolStripMenuItem toolMenuDown = ((ToolStripMenuItem)sender).OwnerItem as ToolStripMenuItem;
                //拿到路径中的工程文件名
                string projectNames = toolMenuDown.Text.Split('工', '程', '文', '件')[0];
                if (projectName == projectNames)//必须是正在操作的工程才可以删除这个工程文件StaicResouce.formCollections
                {
                    StaicResouce.FilesName.Remove(projectNames);//将工程名称删除掉
                    bool delPaper = false;
                    List<HwindowFlowNodeUrseControl> Indextlist = new List<HwindowFlowNodeUrseControl>();//存储临时下标
                    Indextlist.Clear();
                    //获取所有子节点
                    List<string> toolNames = new List<string>();
                    foreach (ToolStripMenuItem toolName in toolMenuDown.DropDownItems)
                    {
                        if (toolName.Text.Contains("任务文件"))
                        {
                            string[] snames = toolName.Text.Split(new char[] { '任', '务', '文', '件' });
                            toolNames.Add(snames[0]);
                        }
                    }
                    for (int i = 0; i < StaicResouce.HomeForms.Count; i++)
                    {
                        HwindowFlowNodeUrseControl hd = StaicResouce.HomeForms[i] as HwindowFlowNodeUrseControl;
                        if (hd.projectName == projectNames)
                        {
                            Indextlist.Add(hd);
                            delPaper = true;
                        }
                        for (int iss = 0; iss < StaicResouce.formCollections.Count; iss++)
                        {
                            foreach (var itemStrings in toolNames)
                            {
                                if (StaicResouce.formCollections[iss].name == itemStrings)
                                {
                                    StaicResouce.formCollections.RemoveAt(iss);
                                }
                            }
                        }
                    }
                    foreach (HwindowFlowNodeUrseControl item in Indextlist)
                    {
                        //将对应相机的工位资源释放
                        if (item.camerFormController != null && projectName == item.projectName)
                        {
                            try
                            {
                                if (item.camerFormController.device != null)
                                {
                                    item.runPaper = false;
                                    item.timer2.Enabled = false;
                                    item.timer3.Enabled = false;
                                    item.timer4.Enabled = false;
                                    item.timer5.Enabled = false;
                                    item.camerFormController?.cancellationTokenSource.Cancel();
                                    item.camerFormController.paper = false;
                                    int check = item.camerFormController.device.Close();
                                    item.camerFormController.device.Dispose();
                                    //SDKSystem.Finalize();//释放资源
                                }
                            }
                            catch (Exception ex)
                            {
                                // 记录错误信息
                                Console.WriteLine($"设备关闭失败，错误码: {ex.Message}");
                            }
                        }
                        //通过对象去删除
                        StaicResouce.HomeForms.Remove(item);
                    }
                    if (true)
                    {
                        //删除TabPage
                        this.tabControl2.TabPages.Clear();
                        //删除工程节点   获取到根节点
                        ToolStripMenuItem toolMenuUp = ((ToolStripMenuItem)toolMenuDown).OwnerItem as ToolStripMenuItem;
                        toolMenuUp.DropDownItems.Remove(toolMenuDown);
                    }
                    //删除工程文件夹
                    if (Directory.Exists(approvePath + projectName))//工程文件路径
                    {
                        Directory.Delete(approvePath + projectName, true);//删除工程文件
                    }
                    //刷新配置界面
                    ConfigForm.GetSingle().Push_Data();

                    //RemoveParent(sender, "delete");
                    MessageBox.Show("已删除该工程文件!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                    //如果有其它工程则自动切换
                    foreach (ToolStripMenuItem item in this.工程管理ToolStripMenuItem.DropDownItems)
                    {
                        切换工程ToolStripMenuItem_Click(item.DropDownItems[2], null);
                        break;
                    }

                    if (this.工程管理ToolStripMenuItem.DropDownItems.Count==0)
                    {
                        projectName = "";
                        MonitoringForm.GetMonitoringForm().DelSum();

                    }
                }
                else
                {
                    MessageBox.Show("删除工程时，请切换至所对应的工程下，再进行删除 工程", "消息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                //删除工程需要重新定义一下名称
                //
                //更新工位监控显示
                MonitoringForm.GetMonitoringForm().Display_Text();
            }
            catch { }
        }
        public void CloseThread()
        {
            for (int i = 0; i < StaicResouce.HomeForms.Count; i++)
            {
                try
                {
                    HwindowFlowNodeUrseControl hd = StaicResouce.HomeForms[i] as HwindowFlowNodeUrseControl;
                    hd.camerFormController?.cancellationTokenSource?.Cancel();
                    if (hd.camerFormController!=null)
                    {
                        hd.camerFormController.paper = false;
                    }
                }
                catch
                {

                }
            }
        }
        /// <summary>
        /// 多方案
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItemCopy_Click(object sender, EventArgs e)
        {
            if (filePath == @"Data\工程文件\")
            {
                MessageBox.Show("维护中");
                return;
            }

            NameCopyForm nameForm = new NameCopyForm();
            nameForm.ShowDialog(this);
            if (nameForm.name.Trim() == "")
            {
                return;
            }
            //当前节点对象
            ToolStripMenuItem current = sender as ToolStripMenuItem;
            //父节点对象
            ToolStripMenuItem parent = current.Tag as ToolStripMenuItem;

            //寻找工程文件
            string[] str = parent.Text.Split(new char[] { '任', '务', '文', '件' }, StringSplitOptions.RemoveEmptyEntries); foreach (HwindowFlowNodeUrseControl hd in StaicResouce.HomeForms)
            {
                if (hd.name == str[0].Trim())
                {
                    CloseSave(hd);
                }
            }
            //源目录
            string sourceDir = filePath + parent.Text;
            //目标目录
            string destDir = filePath + nameForm.name + "任务文件";
            CopyDirectoryRecursively(sourceDir, destDir);
            LoadStation(destDir);
        }
        private void CopyDirectoryRecursively(string sourceDir, string destDir)
        {
            try
            {
                // 检查源目录是否存在
                if (!Directory.Exists(sourceDir))
                {
                    throw new DirectoryNotFoundException("源目录不存在。");
                }
                // 如果目标目录不存在，则创建它
                if (!Directory.Exists(destDir))
                {
                    Directory.CreateDirectory(destDir);
                    if (destDir.Contains("OKNG图片"))
                    {
                        return;
                    }
                }
                // 获取源目录中的所有文件和子目录
                foreach (string file in Directory.GetFiles(sourceDir))
                {
                    // 构造目标文件的路径
                    string destFile = Path.Combine(destDir, Path.GetFileName(file));
                    // 复制文件
                    File.Copy(file, destFile, overwrite: true);
                }

                // 递归复制所有子目录
                foreach (string subDir in Directory.GetDirectories(sourceDir))
                {
                    // 构造目标子目录的路径
                    string destSubDir = Path.Combine(destDir, Path.GetFileName(subDir));
                    // 递归调用 CopyDirectoryRecursively 方法
                    CopyDirectoryRecursively(subDir, destSubDir);
                }
            }
            catch
            {
                MessageBox.Show("多方案失败");
            }
        }
        /// <summary>
        /// 删除任务文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItemMove_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem toolMenu = ((ToolStripMenuItem)sender).OwnerItem as ToolStripMenuItem;
            toolMenu = (toolMenu.OwnerItem as ToolStripMenuItem).DropDownItems[0].OwnerItem as ToolStripMenuItem;
            if (!toolMenu.DropDownItems[2].Enabled)
            {
                MonitoringForm.GetMonitoringForm().Hide();
                RemoveParent(sender, "delete");
            }
            else
            {
                MessageBox.Show("请切换到该工程进行删除任务!", "消息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        /// <summary> 
        /// 删除父菜单和流程图和tabpag
        /// </summary>
        /// <param name="sender"></param>
        private void RemoveParent(object sender, string mode)
        {
            try
            {
                //任务节点
                ToolStripMenuItem toolMenuDown = ((ToolStripMenuItem)sender).OwnerItem as ToolStripMenuItem;
                //工程节点
                ToolStripMenuItem toolMenuUp = ((ToolStripMenuItem)toolMenuDown).OwnerItem as ToolStripMenuItem;
                string projectName = toolMenuUp.Text.Split(new char[] { '工', '程', '文', '件' })[0];
                //删除工程文件  toolMenuDown.Text = aa1   
                string[] str = toolMenuDown.Text.Split(new char[] { '任', '务', '文', '件' }, StringSplitOptions.RemoveEmptyEntries);
                HwindowFlowNodeUrseControl u = null;
                for (int i = 0; i < StaicResouce.HomeForms.Count; i++)
                {
                    HwindowFlowNodeUrseControl hd = StaicResouce.HomeForms[i] as HwindowFlowNodeUrseControl;
                    if (hd.name == str[0].Trim())
                    {
                        u = hd;
                        hd.runPaper = false;
                        hd.timer2.Enabled = false;
                        hd.timer3.Enabled = false;
                        hd.timer4.Enabled = false;
                        hd.timer5.Enabled = false;
                        //将对应相机的工位资源释放
                        if (hd.camerFormController != null)
                        {
                            hd.camerFormController?.CloseCamer();
                        }
                    }
                    if (StaicResouce.formCollections[i].name == str[0].Trim())
                    {
                        StaicResouce.formCollections.RemoveAt(i);
                        break;
                    }
                }
                if (u != null)
                {
                    if (u.camerFormController != null)
                    {
                        u.camerFormController?.cancellationTokenSource.Cancel();
                        u.camerFormController.paper = false;
                    }
                    u.runPaper = false;
                    u.timer2.Enabled = false;
                    u.timer3.Enabled = false;
                    u.timer4.Enabled = false;
                    u.timer5.Enabled = false;
                    u.framesTimeForm.Close();
                    StaicResouce.HomeForms.Remove(u);
                }
                //删除tabpag
                Utiy.RemovePage(tabControl2, str[0].Trim());
                //彻底删除工程文件
                if (mode == "delete")
                {
                    try
                    {
                        //删除监控画面中的界面
                        MonitoringForm.GetMonitoringForm().DelForms(str[0]);
                        Directory.Delete(approvePath + projectName + "\\" + toolMenuDown.Text, true);
                        //删除记录工程文件名的集合
                        StaicResouce.FilesName.Remove(str[0].Trim());
                    }
                    catch { }
                }
                //根点对象
                ToolStripMenuItem head = toolMenuDown.OwnerItem as ToolStripMenuItem;
                //刷新配置界面
                ConfigForm.GetSingle().Push_Data();
                //
                MessageBox.Show("已删除该任务文件!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //删除父菜单
                try { if (head != null) head.DropDownItems.Remove(toolMenuDown); } catch (Exception ex) { }
            }
            catch { }
        }

        /// <summary>
        /// 递归读取子节点的连线状态
        /// </summary> 
        public void AddChildLink(ref int i, string[] tools, TreeNode node)
        {
            if (!(i < tools.Length - 1) || !tools[i + 1].Contains("<—")) return;
            string[] strs = tools[i + 1].Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (TreeNode item in node.Nodes)
            {
                if (item.Name == strs[0])
                {
                    item.Text = strs[1];
                    item.ForeColor = Color.Green;
                    break;
                }
            }
            i++;
            AddChildLink(ref i, tools, node);
        }
        private static object CreateObjectByName(string className, HwindowFlowNodeUrseControl hwindowFlowNode)
        {
            // 通过类名获取类型信息
            Type type = Type.GetType(className);
            if (type == null)
            {
                return null; // 类型不存在
            }

            // 使用Activator.CreateInstance创建类的实例
            return Activator.CreateInstance(type, hwindowFlowNode);
        }
        /// <summary>
        /// 自动保存数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                MonitoringForm.GetMonitoringForm().Show();
                //MonitoringForm.GetMonitoringForm().纵向排列ToolStripMenuItem_Click(sender, e);
                this.Hide();
                e.Cancel = true;
            }
            catch
            {

            }
        }
        public void Savedata()
        {
            //将工程文件路径进行保存，存储程序关闭之前的工程名称
            string paths = @"Data\默认工程文件保存\上一次工程名称.json";
            if (!Directory.Exists(@"Data\默认工程文件保存"))
            {
                Directory.CreateDirectory(@"Data\默认工程文件保存");
            }
            HelpJsons.Write<ProjectDomain>(new ProjectDomain(paths, projectName), paths);

            //将磁盘线程关闭
            delImagePaper = false;
            foreach (HwindowFlowNodeUrseControl hd in StaicResouce.HomeForms)
            {
                CloseSave(hd);
            }
            foreach (HwindowFlowNodeUrseControl hd in StaicResouce.HomeForms)
            {
                new StorageDataController(approvePath + hd.projectName + "\\").Storage(hd);
            }
            //存储每个界面的数据
            // * 保存界面数据 注释
            SDKSystem.Finalize();

            //关闭窗体
            load.Close();
        }
        private void CloseSave(HwindowFlowNodeUrseControl hd)
        {
            hd.FormClosing();
            string state = approvePath + hd.projectName + "\\" + hd.name + "任务文件\\";//例子 ：\Data\工程文件\123工程文件    state
            string flowPath = state + "流程\\";              //例子：\Data\工程文件\123工程文件\流程   flowPath
            string flowFilePath = flowPath + "流程.txt";          //例子：\Data\工程文件\123工程文件\流程\流程.txt   flowFilePath
            if (!Directory.Exists(flowPath))//创建流程文件夹 
            {
                Directory.CreateDirectory(flowPath);
            }
            using (File.Create(flowFilePath)) { }//重新创建工程文件
                                                 //创建或者覆盖界面数据文件夹
            string flowsPaths = state + "界面数据";
            if (!Directory.Exists(flowsPaths))
            {
                //不存在就创建文件夹
                Directory.CreateDirectory(flowsPaths);
            }
            else
            {
                //存在就删除在创建文件夹
                Directory.Delete(flowsPaths, true);
                Directory.CreateDirectory(flowsPaths);
            }

            TreeNodeCollection headNodes = hd.treeView1.Nodes;
            bool delFilePaper = true;
            foreach (TreeNode headNode in headNodes)//新键所有工具根点文件夹
            {
                //在这里将我们的相机工具进行文件的处理
                if (headNode.Name.Equals("相机工具0"))
                {
                    delFilePaper = false;
                }
                string hPath = flowsPaths + "\\" + headNode.Name;//例子：\Data\工程文件\123工程文件\模板匹配0   hPath
                if (!Directory.Exists(hPath))
                {
                    Directory.CreateDirectory(hPath);
                }
                using (StreamWriter writer = new StreamWriter(flowFilePath, append: true))
                {
                    string xxx = headNode.Text;
                    writer.WriteLine(headNode.Tag.ToString() + ":" + headNode.ImageIndex);// 窗体对象+根节点名+根节点显示的图片

                }
            }
            //处理我们的相机工具中的文件了
            if (delFilePaper)
            {
                //如果有这个工具就可以去删除我们的相机文件了
                if (Directory.Exists(state + "相机图片数据"))
                {
                    //有这个文件夹就可以进行覆盖这个文件夹了
                    Directory.Delete(state + "相机图片数据", true);
                    Directory.CreateDirectory(state + "相机图片数据");
                }
            }
        }
        private void socket通信ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SocketForm.GetSocketForm().Show();
        }
        //日志框属性值更改时发生
        private void textBox1_TextChanged_1(object sender, EventArgs e)
        {
            //log.Error(textBox1.Text);
        }
        //工位实时监控画面
        public bool probjectPaper = false;
        private void 工位实时监控ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Hide();
            MonitoringForm.GetMonitoringForm().Show();
            try
            {
                MonitoringForm.GetMonitoringForm().RestoreMDIWindowOrder();
            }catch (Exception ex) { }
            //if (probjectPapecr)
            //{
            //    MonitoringForm.GetMonitoringForm().ToolStripHeng();//MDI窗体排序
            //    probjectPaper = false;
            //}

        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 登录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //窗体自动获得焦点
            EnterUrseForm.GetSingle(this).BringToFront();
            EnterUrseForm.GetSingle(this).Focus();
            EnterUrseForm.GetSingle(this).ShowDialog();
        }
        public void 超级用户()
        {
            新建ToolStripMenuItem.Enabled = true;
            工程管理ToolStripMenuItem.Enabled = true;
            //通信ToolStripMenuItem.Enabled = true;
            修改密码ToolStripMenuItem.Enabled = true;
            treeView1.Enabled = true;
            uiSplitContainer1.SplitterDistance = 254;
        }
        public void 管理员()
        {
            新建ToolStripMenuItem.Enabled = true;
            工程管理ToolStripMenuItem.Enabled = true;
            //通信ToolStripMenuItem.Enabled = true;
            修改密码ToolStripMenuItem.Enabled = false;
            treeView1.Enabled = true;
            uiSplitContainer1.SplitterDistance = 254;
        }
        public void 操作者()
        {
            新建ToolStripMenuItem.Enabled = false;
            工程管理ToolStripMenuItem.Enabled = false;
            //通信ToolStripMenuItem.Enabled = false;
            treeView1.Enabled = false;
            uiSplitContainer1.SplitterDistance = 0;
        }
        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 修改密码ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UrseIDForm.GetSingle().Show();

            //窗体自动获得焦点
            UrseIDForm.GetSingle().BringToFront();
            UrseIDForm.GetSingle().Focus();
            UrseIDForm.GetSingle().Show();
        }
        /// <summary>
        /// 配置界面打开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 配置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ConfigForm.GetSingle().Show();
            //窗体自动获得焦点
            ConfigForm.GetSingle().BringToFront();
            ConfigForm.GetSingle().Focus();
            ConfigForm.GetSingle().Show();
        }
        /// <summary>
        /// 打开任务文件按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></params
        private void 打开任务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem toolMenu = ((ToolStripMenuItem)sender).OwnerItem as ToolStripMenuItem;
            if (!toolMenu.DropDownItems[2].Enabled)
            {
                using (FolderBrowserDialog ofd = new FolderBrowserDialog())
                {
                    ofd.SelectedPath = Application.StartupPath + $"\\Data\\工程文件\\{projectName}\\";
                    // 显示对话框并检查结果
                    DialogResult result = ofd.ShowDialog();
                    if (result == DialogResult.OK)
                    {

                        // 用户点击了“确定”按钮，获取选中的文件夹路径
                        string selectedFolderPath = ofd.SelectedPath;
                        string[] checkNames = selectedFolderPath.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
                        string[] stateNames = selectedFolderPath.Split(new char[] { '任', '务', '文', '件', '\\' }, StringSplitOptions.RemoveEmptyEntries);
                        //获取到任务文件中的名字
                        if (stateNames.Length >= 10)//选择正确的文件打开
                        {
                            string stateName = stateNames[stateNames.Length - 1];

                            if (checkNames[checkNames.Length - 1].Contains("任务文件"))
                            {
                                LoadStation(selectedFolderPath, "", "打开任务");

                                ToolStripMenuItem addMenuItemMove = new ToolStripMenuItem(find_name);

                                //新建任务
                                ToolStripMenuItem removeItem = new ToolStripMenuItem("删除任务");
                                removeItem.Tag = addMenuItemMove;
                                removeItem.Click += MenuItemMove_Click;
                                addMenuItemMove.DropDownItems.Add(removeItem);


                                toolMenu.DropDownItems.Add(addMenuItemMove);
                                //刷新配置界面
                                ConfigForm.GetSingle().Push_Data();

                                MonitoringForm.GetMonitoringForm().纵向排列ToolStripMenuItem_Click(sender, e);
                                MonitoringForm.GetMonitoringForm().Hide();
                            }
                            else
                            {
                                MessageBox.Show("请确认该路径是任务文件!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            }
                        }
                        else
                        {
                            MessageBox.Show("请选择正确的任务文件，选择正确的文件，进行打开", "消息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }

                    }
                }
            }
            else
            {
                MessageBox.Show("请切换到该工程进行添加任务!", "消息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        /// <summary>
        /// 新建工程文件，大工程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 新建工程ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                //新建大工程文件
                CreateForms nameForm = new CreateForms();
                nameForm.ShowDialog(this);
                if (nameForm.name == "")
                {
                    return;
                }
                else if (nameForm.name.Contains("工程文件"))
                {
                    MessageBox.Show("文件名不能包含\"工程文件\"");
                    return;
                }
                //创建大工程文件夹
                string paths = approvePath + nameForm.name;
                //有没有工程文件夹
                if (!Directory.Exists(paths))
                {
                    //将当前tabContorl置为null
                    tabControl2.TabPages.Clear();
                    Directory.CreateDirectory(paths);
                    AddMenuItemStrip(nameForm.name, paths, "更新切换工程");
                    //刷新配置界面
                    ConfigForm.GetSingle().Push_Data();
                }
                else
                {
                    MessageBox.Show("该工程已经存在了!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                probjectPaper = true;
            }
            catch
            {

            }           
        }
        /// <summary>
        /// 预加载工程菜单栏的数据
        /// </summary>
        /// <param name="paths">预加载的路径</param>
        private void AddPreloadMenuItemStrip()
        {
            string[] paths = Directory.GetDirectories(approvePath);
            foreach (string item in paths)
            {
                string directoryName = Path.GetFileName(item);
                AddMenuItemStrip(directoryName, item);
            }

            foreach (ToolStripMenuItem item in 工程管理ToolStripMenuItem.DropDownItems)
            {
                string str = item.ToString().Substring(0, item.ToString().IndexOf("工"));
                if (str == projectName)
                {
                    foreach (ToolStripMenuItem item2 in item.DropDownItems)
                    {
                        if (item2.ToString().Contains("切换该工程"))
                        {
                            item2.Enabled = false;
                            toolStrip = item2;
                            break;
                        }
                    }
                }

            }
        }
        /// <summary>
        ///  添加工程文件，以及任务文件,这里只是添加菜单栏的
        /// </summary>
        /// <param name="name">工程名</param>
        /// <param name="paths">工程路径</param>
        public void AddMenuItemStrip(string name, string pathss, string paper = null)
        {
            //将路径的默认路径进行修改
            filePath = pathss;
            //将工程名称给到工程名称变量
            //projectName = name;
            //将工程名增加到集合当中
            StaicResouce.projectList.Add(name);
            //工程文件的路径
            string paths = approvePath + name;
            //将这个工程给到菜单栏的加载当中
            ToolStripMenuItem menuItem1 = new ToolStripMenuItem(name + "工程文件");
            menuItem1.Name = name + "工程文件";
            //新建任务
            ToolStripMenuItem addMenuItemMove = new ToolStripMenuItem("-新建任务-");
            menuItem1.DropDownItems.Add(addMenuItemMove);
            addMenuItemMove.Tag = menuItem1;
            addMenuItemMove.Click += 新建任务ToolStripMenuItem_Click;
            //打开任务
            ToolStripMenuItem openMenuItemMove = new ToolStripMenuItem("-打开任务-");
            menuItem1.DropDownItems.Add(openMenuItemMove);
            openMenuItemMove.Tag = menuItem1;
            openMenuItemMove.Click += 打开任务ToolStripMenuItem_Click;
            //切换工程
            ToolStripMenuItem verifyMenuItems = new ToolStripMenuItem("-切换该工程-");
            menuItem1.DropDownItems.Add(verifyMenuItems);

            verifyMenuItems.Tag = menuItem1;
            verifyMenuItems.Click += 切换工程ToolStripMenuItem_Click;

            if (paper == "更新切换工程")
            {
                切换工程ToolStripMenuItem_Click(verifyMenuItems, null);
            }

            ////重命名改工程ANewProjectForm
            //ToolStripMenuItem verifyMenuItems1 = new ToolStripMenuItem("-重命名工程-");
            //menuItem1.DropDownItems.Add(verifyMenuItems1);
            //verifyMenuItems1.Tag = menuItem1;
            //verifyMenuItems1.Click += 重命名工程名ToolStripMenuItem_Click;
            //删除工程
            ToolStripMenuItem delsMenuItemMove = new ToolStripMenuItem("-删除工程-");
            menuItem1.DropDownItems.Add(delsMenuItemMove);
            delsMenuItemMove.Tag = menuItem1;
            delsMenuItemMove.Click += 删除工程toolStripMenuItem_Click;
            //读取当前工程文件下的任务文件
            string[] directories = Directory.GetDirectories(paths);
            foreach (string dir in directories)
            {
                string directoryName = Path.GetFileName(dir);
                string[] strs = directoryName.Split(new char[] { '任', '务', '文', '件' });
                ToolStripMenuItem addToolStream = new ToolStripMenuItem(strs[0] + "任务文件");
                //任务菜单的删除任务
                ToolStripMenuItem delToolStream = new ToolStripMenuItem("-删除任务-");
                addToolStream.DropDownItems.Add(delToolStream);//增加一个删除任务
                delToolStream.Tag = addToolStream;//绑定父菜单
                addToolStream.Tag = menuItem1;//绑定父菜单
                delToolStream.Click += MenuItemMove_Click;//点击删除任务事件
                menuItem1.DropDownItems.Add(addToolStream);//增加到根节点中
            }

            //将节点添加到父节点中
            工程管理ToolStripMenuItem.DropDownItems.Add(menuItem1);
            menuItem1.Tag = 工程管理ToolStripMenuItem;
        }
        /// <summary>
        /// 重新命名工程名
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 重命名工程名ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string fuchName = ((ToolStripMenuItem)sender).OwnerItem.Text;
            if (fuchName == projectName + "工程文件")
            {
                ANewProjectForm aNewProjectForm = new ANewProjectForm(projectName, approvePath);
                aNewProjectForm.ShowDialog();
            }
            else
            {
                MessageBox.Show("切换到对应的工程文件，才能执行此操作", "消息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

        }

        ToolStripMenuItem toolStrip = null;
        /// <summary>
        /// 切换工程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void 切换工程ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                //切换工程致命错误对象写入
                string logsPath = @"logs/致命错误.txt";
                StreamWriter streamWriter = new StreamWriter(logsPath);
                try
                {
                    try
                    {
                        if (toolStrip == null)
                        {
                            toolStrip = (sender as ToolStripMenuItem);
                        }
                        toolStrip.Enabled = true;
                        toolStrip = (sender as ToolStripMenuItem);
                        toolStrip.Enabled = false;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("第1305报错出现异常");
                        streamWriter.WriteLine("第1340报错出现异常");
                    }
                    try
                    {
                        foreach (Form1Controller item in StaicResouce.formCollections)
                        {
                            HwindowFlowNodeUrseControl hd = item.hwindowFlowNode;
                            string ii = hd.name;
                            CloseSave(hd);
                            new StorageDataController(approvePath + hd.projectName + "\\").Storage(hd);
                            //将对应相机的工位资源释放
                            if (hd.camerFormController != null && projectName == hd.projectName)
                            {
                                try
                                {
                                    hd.camerFormController.cancellationTokenSource.Cancel();
                                    hd.camerFormController.paper = false;
                                    if (hd.camerFormController.device != null)
                                    {
                                        int check = hd.camerFormController.device.Close();
                                        hd.camerFormController.device.Dispose();

                                    }
                                }
                                catch (Exception ex)
                                {
                                    // 记录错误信息
                                    Console.WriteLine($"设备关闭失败，错误码: {ex.Message}");
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("第1340报错出现异常");
                        streamWriter.WriteLine("第1340报错出现异常");
                    }
                    try
                    {
                        //SDKSystem.Finalize();//释放资源
                        //"工程号:"+HwindowFlowNodeUrseControl.name + HwindowFlowNodeUrseControl.name + "工位画面监视"
                        foreach (FramesTimeForm child in MonitoringForm.GetMonitoringForm().MdiChildren)
                        {
                            child.Close();
                        }
                        //将TabContol控件清空
                        this.tabControl2.TabPages.Clear();
                        string openNameCreate = ((ToolStripMenuItem)sender).OwnerItem.Text;
                        string[] silpName = openNameCreate.Split(new char[] { '工', '程', '文', '件' });
                        projectName = silpName[0];//当前操作的工程
                        string[] openStringName = Directory.GetDirectories(approvePath + silpName[0]);
                        // 将子文件夹路径转换为DirectoryInfo对象，以便访问修改时间
                        var directories = openStringName.Select(path => new DirectoryInfo(path)).ToList();
                        // 按照修改时间排序（升序）
                        directories.Sort((dir1, dir2) => dir1.CreationTime.CompareTo(dir2.CreationTime));
                        if (openStringName.Length > 0)
                        {
                            StaicResouce.homeContolrName.Clear();//将这个存储当前使用的任务清空
                        }
                        foreach (var item in directories)
                        {
                            LoadStation(item.FullName, "开启");
                        }
                        //MonitoringForm.GetMonitoringForm().RestoreMDIWindowOrder();
                        MonitoringForm.GetMonitoringForm().Hide();
                        //更新工位监控显示
                        MonitoringForm.GetMonitoringForm().Display_Text();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("第1340报错出现异常");
                        streamWriter.WriteLine("第1340报错出现异常");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("第1340报错出现异常");
                    streamWriter.WriteLine("第1340报错出现异常");
                }
                streamWriter.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("第1394报错出现异常");
            }
        }
        private bool ShowFilePathNULL()
        {
            if (getHomeFormPaper == false)
            {
                return false;
            }
            //如果filePath路径没变那么就是不能去创建工程文件了
            if (filePath == @"Data\工程文件\")
            {
                MessageBox.Show("请创建工程文件", "消息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                getHomeFormPaper = false;
                return false;
            }
            return true;
        }

        string Dir_GongCheng_Name = "";
        public void Find_GongCheng_Directory(string path)
        {
            if (Directory.Exists(path))
            {
                find_index++;

                string[] strs = path.Split(new char[] { '\\' });
                string endPath = "";
                for (int i = 0; i < strs.Length; i++)
                {
                    if (i != strs.Length - 1)
                    {
                        endPath += strs[i];
                        endPath += "\\";
                    }
                    else
                    {
                        Dir_GongCheng_Name = strs[i] + "副本_" + find_index; ;
                        endPath += strs[i] + "副本_" + find_index;
                    }
                }
                find_path = endPath;
                Find_Directory(find_path);
            }
        }

        /// <summary>
        /// 打开工程文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 打开工程ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //先保存数据
            foreach (HwindowFlowNodeUrseControl hd in StaicResouce.HomeForms)
            {
                CloseSave(hd);
                new StorageDataController(approvePath + hd.projectName + "\\").Storage(hd);
            }
            using (FolderBrowserDialog ofd = new FolderBrowserDialog())
            {
                ofd.SelectedPath = Application.StartupPath + $"\\Data\\工程文件\\";
                // 显示对话框并检查结果
                DialogResult result = ofd.ShowDialog();
                if (result == DialogResult.OK)
                {
                    // 用户点击了“确定”按钮，获取选中的文件夹路径
                    string selectedFolderPath = ofd.SelectedPath;
                    //确定它是否为工程文件
                    string[] pathsString = Directory.GetDirectories(selectedFolderPath);


                    //标志位
                    bool projectPaper = false;
                    foreach (string pathus in pathsString)
                    {
                        if (Path.GetFileName(pathus).Contains("任务文件"))//是工程文件
                        {
                            projectPaper = true;
                            break;
                        }
                    }
                    //判断这个工程文件在文件夹是否存在多的同名的工程
                    if (projectPaper)
                    {
                        Find_GongCheng_Directory(selectedFolderPath);
                        CopyDirectory(selectedFolderPath, find_path);
                        //菜单栏的增加
                        AddMenuItemStrip(Dir_GongCheng_Name, find_path);
                        //将数据同步到集合当中
                        //刷新配置界面
                        ConfigForm.GetSingle().Push_Data();
                    }
                }
            }
        }
        /// <summary>
        /// 递归复制子文件
        /// </summary>
        /// <param name="sourceDir">源文件夹路径</param>
        /// <param name="targetDir">目标文件夹路径</param>
        public void CopyDirectory(string sourceDir, string targetDir)
        {
            // 如果目标文件夹不存在，则创建它
            if (!Directory.Exists(targetDir))
            {
                Directory.CreateDirectory(targetDir);
            }

            // 复制源文件夹中的所有文件到目标文件夹
            foreach (string file in Directory.GetFiles(sourceDir))
            {
                // 获取文件名并构建目标文件路径
                string fileName = Path.GetFileName(file);
                string destFile = Path.Combine(targetDir, fileName);

                // 复制文件
                File.Copy(file, destFile, overwrite: true);  // overwrite为true时会覆盖目标文件
            }

            // 递归复制所有子文件夹
            foreach (string subDir in Directory.GetDirectories(sourceDir))
            {
                // 获取子文件夹的名称并构建目标子文件夹路径
                string subDirName = Path.GetFileName(subDir);
                string destSubDir = Path.Combine(targetDir, subDirName);

                // 递归调用复制子文件夹
                CopyDirectory(subDir, destSubDir);
            }
        }
        private void menuStrip1_MouseEnter(object sender, EventArgs e)
        {
            this.Cursor = Cursors.Default;
        }

        /// <summary>
        /// 保存工程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 保存工程ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //将工程文件路径进行保存，存储程序关闭之前的工程名称
            string paths = @"Data\默认工程文件保存\上一次工程名称.json";
            if (!Directory.Exists(@"Data\默认工程文件保存"))
            {
                Directory.CreateDirectory(@"Data\默认工程文件保存");
            }
            HelpJsons.Write<ProjectDomain>(new ProjectDomain(paths, projectName), paths);

            //将磁盘线程关闭
            delImagePaper = false;
            foreach (HwindowFlowNodeUrseControl hd in StaicResouce.HomeForms)
            {
                string ii = hd.name;
                CloseSave(hd);
            }
            foreach (HwindowFlowNodeUrseControl hd in StaicResouce.HomeForms)
            {
                new StorageDataController(approvePath + hd.projectName + "\\").Storage(hd);
            }

            MessageBox.Show("保存成功!","提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
        }
        /// <summary>
        /// 另存为工程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 另存为ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NameCopyForm nameForm = new NameCopyForm();
            nameForm.ShowDialog(this);

            //这里要获得当前工位的路径
            if (nameForm.name == "")
            {
                return;
            }

            if (tabControl2.SelectedIndex != -1)
            {
                //保存数据
                保存工程ToolStripMenuItem_Click(null, null);

                CopyDirectory("Data\\工程文件\\" + projectName, Application.StartupPath + "\\Data\\工程文件\\" + nameForm.name);

                //菜单栏的增加
                AddMenuItemStrip(nameForm.name, Application.StartupPath + "\\Data\\工程文件\\" + nameForm.name, "更新切换工程");
                //刷新配置界面
                ConfigForm.GetSingle().Push_Data();
               
            }
            else
            {
                MessageBox.Show("该工程任务无,因此无法实现!", "消息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        /// <summary>
        /// 复位所有工位
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            启动所有工位ToolStripMenuItem_Click(sender, e);
        }
        /// <summary>
        /// 清除所有计数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            // 显示确认框
            DialogResult result = MessageBox.Show(
                "请确保当前软件在非运行状态 您确定要执行此操作吗？",
                "确认操作",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question
            );
            bool paper = false;
            foreach (TabPage item in tabControl2.TabPages)
            {
                foreach (TreeNode it in ((HwindowFlowNodeUrseControl)item.Tag).treeView1.Nodes)
                {
                    if (it.Tag is CamerForm)
                    {
                        CamerFormController camerFormController = (it.Tag as CamerForm).controller;
                        if (camerFormController != null)
                        {
                            if (camerFormController.triggerModePaper && camerFormController.triggerSourcePaper && ((HwindowFlowNodeUrseControl)item.Tag).runPaper)
                            {
                                paper = true;
                                MessageBox.Show("软件正在运行状态！ 请点击左侧菜单停止按钮以正确执行该操作", "无法操作", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                goto Label1;
                            }
                        }
                    }
                }
            }
            Label1:

            if (!paper)
            {
                foreach (TabPage item in tabControl2.TabPages)
                {
                    if (result == DialogResult.Yes)
                    {
                        ((HwindowFlowNodeUrseControl)item.Tag).ExecuteAction(1); // 执行确认操作
                    }
                }
                MessageBox.Show("清理操作已执行！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private async void 启动所有工位ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {


                DialogResult = MessageBox.Show("复位成功!", "消息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                if (DialogResult == DialogResult.OK)
                {
                    PaperTrue();
                    // 创建一个 Task 列表，用于保存所有异步任务
                    var tasks = new List<Task>();
                    tasks.Add(Task.Run(() =>
                    {
                        // 使用 Task.Run 异步调用 FuWei()
                        foreach (TabPage item in tabControl2.TabPages)
                        {
                            try
                            {
                                ((HwindowFlowNodeUrseControl)item.Tag).hSmartWindowControl1.SetFullImagePart();
                                ((HwindowFlowNodeUrseControl)item.Tag).framesTimeForm.Hwindow.SetFullImagePart();
                            }
                            catch
                            {

                            }
                            ((HwindowFlowNodeUrseControl)item.Tag).FuWei();
                        }
                    }));
                    // 等待所有异步任务完成
                    await Task.WhenAll(tasks);
                }
            }
            catch (Exception ex)
            {
            }
        }
        //private void 启动所有工位ToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    foreach (TabPage item in tabControl2.TabPages)
        //    {
        //        ((HwindowFlowNodeUrseControl)item.Tag).FuWei();
        //    }
        //    MessageBox.Show("复位成功!", "消息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        //}

        //public  void toolStripMenuItem5_Click(object sender, EventArgs e)
        //{
        //    foreach (TabPage item in tabControl2.TabPages)
        //    {
        //        ((HwindowFlowNodeUrseControl)item.Tag).Tz();
        //    }
        //    MessageBox.Show("停止成功 启动请按复位按钮");
        //}
        public void toolStripMenuItem5_Click(object sender, EventArgs e)
        {
            try
            {
                // 使用 Parallel.ForEach 并发执行 Tz() 方法
                this.PaperFalse();
                AllStopAsync();
                MessageBox.Show("停止成功 启动请按复位按钮", "消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"停止操作时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public void AllStopAsync(string name = "")
        {
            try
            {
                if (name == "")
                {
                    // 使用 Task.Run 异步调用 FuWei()
                    foreach (TabPage item in tabControl2.TabPages)
                    {
                        ((HwindowFlowNodeUrseControl)item.Tag).Tz();
                    }
                }
                else
                {
                    foreach (TabPage item in tabControl2.TabPages)
                    {
                        if (((HwindowFlowNodeUrseControl)item.Tag).name != name)
                        {
                            ((HwindowFlowNodeUrseControl)item.Tag).Tz();
                        }
                    }
                }
            }
            catch 
            {
                // 异常处理逻辑
              //  Console.WriteLine(ex.Message); // 可根据需求修改
            }
        }
        public async void PaperFalse()
        {
            try
            {
                MonitoringForm.GetMonitoringForm().参数设置窗口ToolStripMenuItem.Enabled = true;
            }
            catch
            {

            }
            var tasks = new List<Task>();
            foreach (TabPage item in tabControl2.TabPages)
            {
                tasks.Add(Task.Run(async () =>
                {
                    try
                    {
                        ((HwindowFlowNodeUrseControl)item.Tag).runPaper = false;
                        ((HwindowFlowNodeUrseControl)item.Tag).treeView1.Enabled = true;
                        if (((HwindowFlowNodeUrseControl)item.Tag).camerFormController?.device != null)
                        {

                            ((HwindowFlowNodeUrseControl)item.Tag).camerFormController.device.StreamGrabber.FrameGrabedEvent -= ((HwindowFlowNodeUrseControl)item.Tag).camerFormController.StreamGrabber_FrameGrabedEvent;

                            await Task.Delay(50).ConfigureAwait(false);

                            ((HwindowFlowNodeUrseControl)item.Tag).camerFormController.device.StreamGrabber.FrameGrabedEvent += ((HwindowFlowNodeUrseControl)item.Tag).camerFormController.StreamGrabber_FrameGrabedEvent;


                        }
                    }
                    catch
                    {

                    }
                }));
            }
            await Task.WhenAll(tasks);
        }
        public void PaperTrue()
        {
            var tasks = new List<Task>();
            foreach (TabPage item in tabControl2.TabPages)
            {
                tasks.Add(Task.Run(() =>
                {
                    ((HwindowFlowNodeUrseControl)item.Tag).runPaper = true;
                }));
            }
        }
    }
}
